import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:intl/intl.dart';
import 'dart:math' as math;

class DashboardScreen extends StatefulWidget {
  const DashboardScreen({Key? key}) : super(key: key);

  @override
  State<DashboardScreen> createState() => _DashboardScreenState();
}

class _DashboardScreenState extends State<DashboardScreen> {
  final List<Color> _gradientColors = [
    const Color(0xff23b6e6),
    const Color(0xff02d39a),
  ];

  // ۋاقىتلىق سېتىش سانلىق مەلۇماتلىرى
  final List<Map<String, dynamic>> _recentSales = List.generate(
    10,
    (index) => {
      'id': 'S-${(1000 + index).toString()}',
      'customer': 'خېرىدار ${index + 1}',
      'amount': (100 + math.Random().nextInt(900)).toDouble(),
      'date': DateTime.now().subtract(Duration(days: index)),
      'status': _getRandomStatus(),
      'items': math.Random().nextInt(10) + 1,
    },
  );

  // تەسادىپىي ھالەتنى قايتۇرىدۇ
  static String _getRandomStatus() {
    final statuses = ['پۈتتى', 'كېچىكتى', 'كۈتۈۋاتىدۇ', 'ئەمەلدىن قالدى'];
    return statuses[math.Random().nextInt(statuses.length)];
  }

  // سېتىش سانلىق مەلۇماتلىرى
  final List<double> _weeklySales = List.generate(
    7,
    (index) => (500 + math.Random().nextInt(1000)).toDouble(),
  );

  // ئاخبارات ھەم يېڭىلىقلار
  final List<Map<String, dynamic>> _notifications = [
    {
      'title': 'ئامباردا مال ئاز قالدى',
      'message': '5 خىل مالنىڭ سانى تۆۋەن چەككە يەتتى، تولۇقلىۋېلىڭ',
      'time': DateTime.now().subtract(const Duration(hours: 1)),
      'type': 'warning',
    },
    {
      'title': 'بۈگۈنكى مال سېتىلىش رېكورتى',
      'message': 'بۈگۈن 5000 يۈەندىن ئارتۇق مال سېتىلدى',
      'time': DateTime.now().subtract(const Duration(hours: 3)),
      'type': 'info',
    },
    {
      'title': 'يېڭى خېرىدار',
      'message': '3 يېڭى خېرىدار تىزىمغا قوشۇلدى',
      'time': DateTime.now().subtract(const Duration(hours: 5)),
      'type': 'success',
    },
    {
      'title': 'تۆلەم ئەسكەرتىش',
      'message': '2 قېرىندىشىم شىركىتى تۆلەمنى كېچىكتۈردى',
      'time': DateTime.now().subtract(const Duration(days: 1)),
      'type': 'error',
    },
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('باش بەت'),
        actions: [
          IconButton(
            icon: const Icon(Icons.notifications),
            onPressed: () {
              // ئۇقتۇرۇشلار بېتىگە بېرىش
            },
          ),
          IconButton(
            icon: const Icon(Icons.settings),
            onPressed: () {
              // تەڭشەكلەر بېتىگە بېرىش
            },
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildWelcomeCard(),
              const SizedBox(height: 20),
              _buildSummaryCards(),
              const SizedBox(height: 20),
              _buildSalesChart(),
              const SizedBox(height: 20),
              _buildRecentSalesAndNotifications(),
            ],
          ),
        ),
      ),
    );
  }

  // قارشى ئېلىش كارتىسى
  Widget _buildWelcomeCard() {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Row(
          children: [
            CircleAvatar(
              radius: 30,
              backgroundColor: Colors.blue.shade100,
              child: const Icon(
                Icons.person,
                size: 30,
                color: Colors.blue,
              ),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    'خوش كەلدىڭىز، مۇدىر!',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    'بۈگۈن: ${DateFormat('yyyy-MM-dd').format(DateTime.now())}',
                    style: TextStyle(
                      color: Colors.grey.shade600,
                    ),
                  ),
                ],
              ),
            ),
            IconButton(
              icon: const Icon(Icons.refresh),
              onPressed: () {
                // مەلۇماتلارنى يېڭىلاش
                setState(() {});
              },
            ),
          ],
        ),
      ),
    );
  }

  // قىسقىچە ھېسابات كارتىلىرى
  Widget _buildSummaryCards() {
    return GridView.count(
      crossAxisCount: 2,
      crossAxisSpacing: 16,
      mainAxisSpacing: 16,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      children: [
        _buildSummaryCard(
          'بۈگۈنكى سېتىش',
          '¥${(1000 + math.Random().nextInt(9000)).toString()}',
          Icons.shopping_cart,
          Colors.blue,
          '+ 12.5%',
          true,
        ),
        _buildSummaryCard(
          'بۇ ئايدىكى كىرىم',
          '¥${(15000 + math.Random().nextInt(85000)).toString()}',
          Icons.attach_money,
          Colors.green,
          '+ 8.3%',
          true,
        ),
        _buildSummaryCard(
          'يېڭى خېرىدارلار',
          '${math.Random().nextInt(50) + 5}',
          Icons.people,
          Colors.orange,
          '+ 5.7%',
          true,
        ),
        _buildSummaryCard(
          'ئامباردىكى مال',
          '${math.Random().nextInt(500) + 50}',
          Icons.inventory_2,
          Colors.purple,
          '- 2.3%',
          false,
        ),
      ],
    );
  }

  // قىسقىچە ھېسابات كارتىسى
  Widget _buildSummaryCard(
    String title,
    String value,
    IconData icon,
    Color color,
    String change,
    bool isPositive,
  ) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  title,
                  style: TextStyle(
                    color: Colors.grey.shade600,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                Icon(
                  icon,
                  color: color,
                ),
              ],
            ),
            const SizedBox(height: 20),
            Text(
              value,
              style: const TextStyle(
                fontSize: 22,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 8),
            Row(
              children: [
                Icon(
                  isPositive ? Icons.arrow_upward : Icons.arrow_downward,
                  color: isPositive ? Colors.green : Colors.red,
                  size: 16,
                ),
                const SizedBox(width: 4),
                Text(
                  change,
                  style: TextStyle(
                    color: isPositive ? Colors.green : Colors.red,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // سېتىش سىزىقلىق دىئاگراممىسى
  Widget _buildSalesChart() {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  'ھەپتىلىك سېتىش',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                DropdownButton<String>(
                  value: 'ھەپتىلىك',
                  items: ['ھەپتىلىك', 'ئايلىق', 'يىللىق']
                      .map((e) => DropdownMenuItem<String>(
                            value: e,
                            child: Text(e),
                          ))
                      .toList(),
                  onChanged: (value) {},
                ),
              ],
            ),
            const SizedBox(height: 20),
            SizedBox(
              height: 200,
              child: LineChart(
                _mainData(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // سىزىقلىق دىئاگرامما سانلىق مەلۇماتلىرى
  LineChartData _mainData() {
    return LineChartData(
      gridData: FlGridData(
        show: true,
        drawVerticalLine: true,
        horizontalInterval: 100,
        verticalInterval: 1,
        getDrawingHorizontalLine: (value) {
          return FlLine(
            color: Colors.grey.shade200,
            strokeWidth: 1,
          );
        },
        getDrawingVerticalLine: (value) {
          return FlLine(
            color: Colors.grey.shade200,
            strokeWidth: 1,
          );
        },
      ),
      titlesData: FlTitlesData(
        show: true,
        rightTitles: AxisTitles(
          sideTitles: SideTitles(showTitles: false),
        ),
        topTitles: AxisTitles(
          sideTitles: SideTitles(showTitles: false),
        ),
        bottomTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            getTitlesWidget: (value, meta) {
              final List<String> titles = [
                'دۈ',
                'سە',
                'چا',
                'پە',
                'جۈ',
                'شە',
                'يە'
              ];
              final int index = value.toInt();
              if (index >= 0 && index < titles.length) {
                return Padding(
                  padding: const EdgeInsets.only(top: 8.0),
                  child: Text(
                    titles[index],
                    style: TextStyle(
                      color: Colors.grey.shade600,
                      fontWeight: FontWeight.bold,
                      fontSize: 12,
                    ),
                  ),
                );
              }
              return const SizedBox.shrink();
            },
            reservedSize: 30,
          ),
        ),
        leftTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            getTitlesWidget: (value, meta) {
              return Text(
                '${value.toInt()}',
                style: TextStyle(
                  color: Colors.grey.shade600,
                  fontWeight: FontWeight.bold,
                  fontSize: 12,
                ),
              );
            },
            reservedSize: 40,
            interval: 200,
          ),
        ),
      ),
      borderData: FlBorderData(
        show: true,
        border: Border.all(color: Colors.grey.shade300),
      ),
      minX: 0,
      maxX: 6,
      minY: 0,
      maxY: 1000,
      lineBarsData: [
        LineChartBarData(
          spots: _weeklySales
              .asMap()
              .entries
              .map((entry) => FlSpot(entry.key.toDouble(), entry.value))
              .toList(),
          isCurved: true,
          gradient: LinearGradient(
            colors: _gradientColors,
          ),
          barWidth: 5,
          isStrokeCapRound: true,
          dotData: FlDotData(
            show: true,
          ),
          belowBarData: BarAreaData(
            show: true,
            gradient: LinearGradient(
              colors: _gradientColors
                  .map((color) => color.withOpacity(0.3))
                  .toList(),
            ),
          ),
        ),
      ],
    );
  }

  // يېقىنقى سېتىشلار ۋە ئۇقتۇرۇشلار
  Widget _buildRecentSalesAndNotifications() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Expanded(
          flex: 3,
          child: Card(
            elevation: 2,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text(
                        'يېقىنقى سېتىشلار',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      TextButton(
                        onPressed: () {
                          // ھەممىنى كۆرۈش بېتىگە ئۆتۈش
                        },
                        child: const Text('ھەممىنى كۆرۈش'),
                      ),
                    ],
                  ),
                  const SizedBox(height: 8),
                  ListView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    itemCount:
                        _recentSales.length > 5 ? 5 : _recentSales.length,
                    itemBuilder: (context, index) {
                      final sale = _recentSales[index];
                      return ListTile(
                        contentPadding: EdgeInsets.zero,
                        leading: CircleAvatar(
                          backgroundColor: Colors.blue.shade100,
                          child: Text(
                            sale['customer'][0],
                            style: const TextStyle(color: Colors.blue),
                          ),
                        ),
                        title: Text(sale['customer']),
                        subtitle: Text(
                          DateFormat('yyyy-MM-dd').format(sale['date']),
                        ),
                        trailing: Text(
                          '¥${sale['amount'].toStringAsFixed(2)}',
                          style: const TextStyle(
                            fontWeight: FontWeight.bold,
                            color: Colors.blue,
                          ),
                        ),
                      );
                    },
                  ),
                ],
              ),
            ),
          ),
        ),
        const SizedBox(width: 16),
        Expanded(
          flex: 2,
          child: Card(
            elevation: 2,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text(
                        'ئۇقتۇرۇشلار',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      IconButton(
                        onPressed: () {
                          // ئۇقتۇرۇشلارنى يېڭىلاش
                        },
                        icon: const Icon(Icons.refresh, size: 20),
                      ),
                    ],
                  ),
                  const SizedBox(height: 8),
                  ListView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    itemCount: _notifications.length,
                    itemBuilder: (context, index) {
                      final notification = _notifications[index];
                      return _buildNotificationItem(notification);
                    },
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  // ئۇقتۇرۇش تۈرىنى رەڭ قايتۇرىدۇ
  Color _getNotificationColor(String type) {
    switch (type) {
      case 'warning':
        return Colors.orange;
      case 'success':
        return Colors.green;
      case 'error':
        return Colors.red;
      default:
        return Colors.blue;
    }
  }

  // ئۇقتۇرۇش تۈرىنى ئىكونكا قايتۇرىدۇ
  IconData _getNotificationIcon(String type) {
    switch (type) {
      case 'warning':
        return Icons.warning_amber_rounded;
      case 'success':
        return Icons.check_circle;
      case 'error':
        return Icons.error;
      default:
        return Icons.info;
    }
  }

  // ئۇقتۇرۇش تۈرىنى
  Widget _buildNotificationItem(Map<String, dynamic> notification) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color:
                  _getNotificationColor(notification['type']).withOpacity(0.1),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Icon(
              _getNotificationIcon(notification['type']),
              color: _getNotificationColor(notification['type']),
              size: 20,
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  notification['title'],
                  style: const TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 14,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  notification['message'],
                  style: TextStyle(
                    color: Colors.grey.shade600,
                    fontSize: 12,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  _getTimeAgo(notification['time']),
                  style: TextStyle(
                    color: Colors.grey.shade500,
                    fontSize: 11,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // ۋاقىت پەرقىنى ھېسابلايدۇ
  String _getTimeAgo(DateTime time) {
    final now = DateTime.now();
    final difference = now.difference(time);

    if (difference.inDays > 0) {
      return '${difference.inDays} كۈن ئىلگىرى';
    } else if (difference.inHours > 0) {
      return '${difference.inHours} سائەت ئىلگىرى';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes} مىنۇت ئىلگىرى';
    } else {
      return 'ھازىرلا';
    }
  }
}
